package com.cn.ccp.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.cn.ccp.bean.MenuBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.listener.RegisterPropertiesUtils;
import com.cn.ccp.listener.SerialCodeUtils;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;

public class LoginAction extends BaseAction {
	private Logger log = Logger.getLogger(LoginAction.class);
	private String userName ;
	private String password ;
	private UserBean bean;
	private String diskSerial;
	private String serialNumber;
	
	
	public String submit(){
//		log.info("userName:"+userName+"  password:"+password);
		
		Object uName = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("userName");
		log.info("------------uName = "+uName);
		if(uName == null || "".equalsIgnoreCase(uName.toString().trim())){
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage("formid", new FacesMessage(getMessages("login_page_label_error_1")));
			return "";
		}
		userName = uName.toString().trim();
		
		Object pass = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("userPassword");
//		log.info("------------pass = "+pass);
		if(pass == null || "".equalsIgnoreCase(pass.toString().trim())){
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage("formid", new FacesMessage(getMessages("login_page_label_error_2")));
			return "";
		}
		password = pass.toString().trim();
		log.info("password = "+password);
		bean = (UserBean) getUserService().loginCheckUseLoginName(userName,password);
		log.info(bean);
		if(bean == null)
			bean = (UserBean) getUserService().loginCheck(userName,password);
//		log.info(bean);
		if(bean == null){
			showMsg("formid",  "login_page_label_error");
			userName = "";
			password = "" ;
			return "";
		}
		
		if( bean.getImage() != null  && isImage(bean.getImage().trim())){
			try {
				String ext = bean.getImage().split("\\.")[1];
				//删除多余的头像文件
				File f = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+bean.getId() );
				if(f.isDirectory()){
					File[] fs = f.listFiles();
					for(File ff : fs)
						if(ff.getName().indexOf("head-image") >= 0)
							ff.delete();
				}
				
				File des = new File(CCPContants.SYS_PATH + "tempfile"+File.separator+bean.getId() + File.separator +"head-image."+ext);
				des.delete();
				String imagePath = CCPContants.getFilePath(bean.getImage() , getFilePathService(),bean.getFile_path_id() , bean.getId());
				File file = new File(imagePath);
				
				String headImagePath = file.getParent()+File.separator + "head-image."+ext;
				file.renameTo(new File(headImagePath));
				
				if(file.exists())
					bean.setHeadImage("tempfile/"+bean.getId()+"/"+"head-image."+ext);
				else
					bean.setHeadImage(null);
			} catch (Exception e) {
				bean.setHeadImage(null);
			}
		}else
			bean.setHeadImage(null);
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		session.setAttribute(Contants.USER_SESSION_BEAN ,bean);
		session.setAttribute(Contants.FILE_TYPE_FILE , CCPContants.uploadFileLayout+";"+CCPContants.uploadVideoLayout);
		session.setAttribute(Contants.FILE_TYPE_IMAGE ,CCPContants.imageLayout);
		log.info("-------------------"+session);
		
//		List<MenuBean> menuList = getMenuService().getMenuListByUserID(""+bean.getId());
//		session.setAttribute(Contants.USER_SESSION_MENU ,menuList);
		
		
		LinkedHashMap<MenuBean ,List<MenuBean> > menuMap = new LinkedHashMap<MenuBean ,List<MenuBean>>();
		
		List<MenuBean> menuList = getMenuService().getMenuByUserId(bean.getId());
		for(MenuBean m : menuList){
			if(m.getParentid() == 0){//一级菜单
				menuMap.put(m, new ArrayList<MenuBean>());
			}else{//二级菜单
				Iterator<MenuBean> iters = menuMap.keySet().iterator();
				while(iters.hasNext()){
					MenuBean bean = iters.next();
					if(bean.getId() == m.getParentid()){
						menuMap.get(bean).add(m);
					}
				}
			}
		}
				 
		session.setAttribute(Contants.USER_SESSION_MENU ,menuMap);
		return SUCCESS;
	 
	}

	/**
	 *  是图片
	 * @param path
	 * @return
	 */
	 private boolean isImage(String path){
		 path = path.toLowerCase();
		 if(path.endsWith(".png") || path.endsWith(".jpg"))
			 return true;
		 else
			 return false;
	 }
	
	
	public String logout(){
		log.info("------------logout()-------------------");
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		session.removeAttribute(Contants.USER_SESSION_BEAN);
		((Map)session.getAttribute(Contants.USER_SESSION_MENU)).clear();
		session.removeAttribute(Contants.USER_SESSION_MENU);
		session.invalidate();
		return "logout";
	}
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public UserBean getBean() {
		return bean;
	}

	public void setBean(UserBean bean) {
		this.bean = bean;
	}

	public String getDiskSerial() {
		return SerialCodeUtils.getMachineCode();
	}

	public String getSerialNumber() {
		return serialNumber;
	}

	public void setSerialNumber(String serialNumber) {
		this.serialNumber = serialNumber;
	}
	
	public String sysRegist(){
		log.info("------------serialNumber = "+serialNumber);
		RegisterPropertiesUtils rUtil = RegisterPropertiesUtils.getInstance();
		rUtil.setSerialCode(serialNumber);
		
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
		session.removeAttribute(Contants.USER_SESSION_BEAN);
		session.removeAttribute(Contants.USER_SESSION_MENU);
		session.invalidate();
		return "loginSucess";
	}
 
	
}
